﻿using Microsoft.Extensions.Configuration;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using Quartz.NET.Web.Extensions;
using Quartz.NET.Web.Models;
using Serilog;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace Quartz.NET.Web.Utility
{
    public class HttpResultfulJob : IJob
    {
        readonly IHttpClientFactory httpClientFactory;
        readonly IFreeSql freeSql;
        /// <summary>
        /// 2020.05.31增加构造方法
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="httpClientFactory"></param>
        public HttpResultfulJob(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory, IFreeSql _fsql)
        {
            this.httpClientFactory = httpClientFactory;
            freeSql = _fsql;
            //serviceProvider.GetService()
        }
        public async Task Execute(IJobExecutionContext context)
        {
            DateTime dateTime = DateTime.Now;
            TaskOptions taskOptions = context.GetTaskOptions();

            string httpMessage = "";
            HttpResponseMessage response = null;
            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            if (taskOptions == null)
            {
                Log.Warning(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", "未到找作业或可能被移除", true);
                return;
            }
            TaskLog lg = new TaskLog();
            lg.BeginDate = dateTime.ToString("yyyy-MM-dd HH:mm:sss");
            Console.WriteLine($"作业[{taskOptions.taskName}]开始:{lg.BeginDate}");
            if (string.IsNullOrEmpty(taskOptions.apiUrl) || taskOptions.apiUrl == "/")
            {
                Log.Information($"{trigger.Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}未配置url,");
                return;
            }

            try
            {
                Dictionary<string, string> header = new Dictionary<string, string>();

                using (var client = httpClientFactory.CreateClient())
                {
                    if (!string.IsNullOrEmpty(taskOptions.authKey)
                 && !string.IsNullOrEmpty(taskOptions.authValue))
                    {
                        client.DefaultRequestHeaders.Add(taskOptions.authKey.Trim(), taskOptions.authValue.Trim());
                    }
                    if (taskOptions.requestType?.ToLower() == "get")
                    {
                        string apiUrl = taskOptions.apiUrl;
                        if (!string.IsNullOrWhiteSpace(taskOptions.apiParams))
                        {
                            apiUrl += taskOptions.apiParams;
                        }
                        response = await client.GetAsync(apiUrl);

                    }
                    else
                    {
                        HttpContent content = new StringContent(taskOptions.apiParams);
                        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                        response = await client.PostAsync(taskOptions.apiUrl, content);
                    }
                }

                httpMessage = await response.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {
                httpMessage = ex.Message;
            }

            try
            {
                lg.EndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string logContent = $"{(string.IsNullOrEmpty(httpMessage) ? "OK" : httpMessage)}\r\n";

                lg.taskId = taskOptions.Id;
                lg.taskName = taskOptions.taskName;
                lg.Msg = logContent;
                // freeSql.Insert(lg);
            }
            catch (Exception ex)
            {
                lg.Msg = ex.Message;
                Log.Error("任务执行出错：" + ex.Message);
            }
            int r = freeSql.Insert(lg).ExecuteAffrows();

            //   Console.WriteLine(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
            return;
        }
    }
}
